﻿namespace TVersityDotNet.MediaLib
{
    using System;
    using System.Collections.ObjectModel;
    using System.Runtime.Serialization;
    using System.Xml.Linq;

    [DataContractAttribute]
    public class MediaLibResponseItem
    {
        public const string Namespace_DC = "http://purl.org/dc/elements/1.1/";
        public const string Namespace_Upnp = "urn:schemas-upnp-org:metadata-1-0/upnp/";
        public const string Namespace_Base = "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/";

        [DataMember]
        public string Id { get; set; }
        [DataMember]
        public string Title { get; set; }
        [DataMember]
        public MediaLibClassType SearchClass { get; set; }
        [DataMember]
        public XElement RawXml { get; set; }
        [DataMember]
        public string ParentId { get; set; }

        [DataMember]
        public static Collection<string> SearchContainerClass
        {
            get
            {
                return SearchClassTypeName.ListOfNames;
            }
            private set { }
        }
        
        public MediaLibResponseItem(XElement xmlElement)
        {
            if (xmlElement != null && xmlElement.Element(XName.Get("class", MediaLibResponseItem.Namespace_Upnp)) != null)
            {
                this.SearchClass = SearchClassTypeName.GetTypeBySearchClassName(xmlElement.Element(XName.Get("class", MediaLibResponseItem.Namespace_Upnp)).Value);
                this.RawXml = xmlElement;
                this.ProcessXmlElement();
            }
            else 
                this.SearchClass = MediaLibClassType.NoClass;
        }

        public MediaLibResponseItem()
        {
            this.SearchClass = MediaLibClassType.NoClass;
            this.Title = String.Empty;
        }

        public void ProcessXmlElement()
        {
            if (this.SearchClass != MediaLibClassType.NoClass)
            {                
                this.Title = this.RawXml.Element(XName.Get("title", MediaLibResponseItem.Namespace_DC)).Value;
                this.Id = this.RawXml.Attribute("id").Value;
                this.ParentId = this.RawXml.Attribute("parentID").Value;
            }
        }

        public override string ToString()
        {
            return this.Title;
        }
    }
}
